<?php

class tvbcom_category extends Model{
	public static function getTableName(){
		return 'tvbcom_category';
	}

	public function getParent()
	{
		$sql = 'select * from '.self::getTableName().' where parent_id=0';
		return Model::$dbo['r']->findBySql(__class__,$sql);
	}

	public function getSub($parentid, &$json_data)
	{
//		$sql = 'select * from '.self::getTableName().' where parent_id='.$parentid;
		$ret =  Model::$dbo['r']->find(__class__,'parent_id=?',array($parentid));
		if (count($ret) == 0)
		{
			$json_data['child'] = array();
			return ;
		}
		else
		{
			$j=0;
			foreach ($ret as $sub)
			{
				$child_data[$j] = array('id'=>$sub->id, 'name'=>$sub->system_label);
				$this->getSub($sub->id,$child_data[$j]);
				$j++;
			}
			$json_data['child'] = $child_data;
		}
	}

	public function getSubCategorys($id = 0)
	{
		empty($id)	&&	$id	=	0;
		//$sql = 'select * from '.self::getTableName().' where parent_id='.$id;
		//$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		$ret =  Model::$dbo['r']->find(__class__,'parent_id=?',array($id));
		$res =	Model::object2array($ret);

		$tmp =	array();
		if (empty($id))
		{
			$tmp[0]	=	'Please Select...';
		}

		if (is_array($res))
		{
			foreach ($res	as	$subCategory)
			{
				$tmp[$subCategory['id']]=	$subCategory['system_label'];
			}
		}
		return	$tmp;
	}

	/**
	 * get parent name according to child id
	 *
	 * @param int $child_id : child id
	 * @use by : action/ProgrammeGetAction.class.php
	 */
	public static function getParentName($child_id, $parent_id)
	{
		$sql = 'select a.system_label as parent,b.system_label as child from '.self::getTableName().' a left join '.self::getTableName().' b on b.parent_id=a.id where b.system_label=\''.$child_id."' and b.parent_id='{$parent_id}'"; 
		$ret = Model::$dbo['r']->findBySql(__class__,$sql);
		return isset($ret[0]) ? $ret[0]->parent : '';
	}

    /**
     * get parent and child name according to id
     *
     * @param   Int $ID
     * @return  Array
     */
    public function getParentChildName($id)
    {
        $sql=   '
            SELECT
                a.system_label      AS  child,
                b.system_label      AS  parent
            FROM
                tvbcom_category AS a LEFT JOIN tvbcom_category AS b ON (b.id = a.parent_id)
            WHERE
                a.id = "'. $id .'"
            ';
        $ret=   Model::$dbo['r']->findBySql(__class__, $sql);
        return  isset($ret[0])  ?   $ret[0] :   NULL;
    }

	/**
	 * Get maincategory id by subcategory id
	 *
	 * @param Int $subCategoryId 
	 * @return Int
	 */
	public static function getMainCategoryId($subCategoryId){
		$sql = 'select parent_id,id from tvbcom_category where id=:id';
		$ret = Model::selectBySql($sql,array(':id'=>$subCategoryId));
		if(empty($ret) || empty($ret[0]['parent_id'])) return $subCategoryId;
		return self::getMainCategoryId($ret[0]['parent_id']);
	}
}
?>
